﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using MM.DBUtility;
using MM.Common;

namespace MobileManager.Customer
{
    public partial class CcostQuery : System.Web.UI.Page
    {
        private MM.Model.T_Users userModel;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurUser"] == null)
            {
                Response.Redirect("Login.aspx");
                return;
            }
            else
            {
                userModel = (MM.Model.T_Users)Session["CurUser"];
            }
            if (!IsPostBack)
            {
                BindDdlCustomer(ref ddlCustomer);

                inputDateFrom.Value = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd");
                inputDateTo.Value = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");

                GVDataBind();
            }
        }

        private void BindDdlCustomer(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query(string.Format("SELECT a.CNO,a.CNO+'-'+ b.CName as Name FROM T_User_Customer a,T_Customers b WHERE a.CNO=b.CNO AND a.UserID='{0}'", userModel.UserID)).Tables[0];
            ddl.DataValueField = "CNO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }

        #region GV Bind
        private void GVDataBind()
        {
            string strSQL = string.Format("SELECT CostDayTime,CNO,SUM(SendNum) as AllSendNum,SUM(CostMoney) as AllCostMoney FROM T_Cost WHERE CreateTime BETWEEN '{0}' AND '{1}'", inputDateFrom.Value, Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));
            strSQL += string.Format(" AND CNO='{0}'", ddlCustomer.SelectedValue);
            strSQL += " GROUP BY CostDayTime,CNO ";

            if (DateTime.Now.ToString("yyyy-MM-dd").Equals(inputDateTo.Value))
            {
                if (GetDayNowData())
                {
                    strSQL += string.Format("UNION ALL SELECT CostDayTime,CNO,SUM(SendNum) as AllSendNum,SUM(CostMoney) as AllCostMoney FROM T_Cost_Temp WHERE CostDayTime='{0}' AND CNO='{1}' GROUP BY CostDayTime,CNO ", inputDateTo.Value, ddlCustomer.SelectedValue);
                }
            }

            DataTable dt = DbHelperSql.Query(strSQL).Tables[0];
            DbHelperSql.ExecuteSql(string.Format("DELETE FROM T_Cost_Temp WHERE CostDayTime='{0}' AND CNO='{1}' ", inputDateTo.Value, ddlCustomer.SelectedValue));
            GVinfo.DataSource = dt;
            GVinfo.DataBind();
        }
        private bool GetDayNowData()
        {
            bool bolResult = false;
            //在规则中取得正在使用的通道信息
            string strCNO = ddlCustomer.SelectedValue;
            DataTable dtChannelNO = DbHelperSql.Query(string.Format("SELECT DISTINCT a.ChannelNO,a.ChannelPrice FROM T_Channel a,T_Rules b WHERE a.ChannelNO=b.ChannelNO AND b.CNO='{0}'", strCNO)).Tables[0];
            if (dtChannelNO != null && dtChannelNO.Rows.Count > 0)
            {
                ArrayList SQLlist = new ArrayList();
                DataTable dtProvinceID = null;
                object OSIMCountByPID = null, OSIMAllCountByPID = null, OChannelRCountByPID = null;
                string strChannelNO = string.Empty, strChannelPrice = string.Empty, strProvinceID = string.Empty;
                string strDayTime = DateTime.Now.ToString("yyyy-MM-dd");//当天日期
                int intSIMCountByPID = 0, intSIMAllCountByPID = 0;//当前客户编号+通道编号+省份的SMI条数，当前省份的SMI条数
                int intChannelRCountByPID = 0;//当前客户编号+通道编号+省份的通道返回记录数
                double dbeCountByPID = 0, dbeAllCount = 0, dbeAllMoney = 0;//当前客户编号+通道编号+省份的实际条数(计算后)，当前客户编号+通道编号的实际条数(计算后)
                double dbeCNORate = 0.8;//前客户编号的数据显示比例


                //取得当前客户编号的数据显示比例
                try
                {
                    if (!string.IsNullOrEmpty(userModel.DataRate))
                        dbeCNORate = Convert.ToDouble(userModel.DataRate);
                }
                catch { }

                foreach (DataRow rowChannelNO in dtChannelNO.Rows)
                {
                    //通过客户编号和通道编号，在规则中取得正在使用的省份信息
                    dbeAllCount = 0; dbeAllMoney = 0;//初始化总记录数
                    strChannelNO = rowChannelNO["ChannelNO"].ToString();
                    strChannelPrice = rowChannelNO["ChannelPrice"].ToString();
                    dtProvinceID = DbHelperSql.Query(string.Format("SELECT DISTINCT ProvinceID FROM T_Rules WHERE Status='1' AND CNO='{0}' AND ChannelNO='{1}'", strCNO, strChannelNO)).Tables[0];
                    if (dtProvinceID != null && dtProvinceID.Rows.Count > 0)
                    {
                        foreach (DataRow rowProvinceID in dtProvinceID.Rows)
                        {
                            strProvinceID = rowProvinceID["ProvinceID"].ToString();
                            intSIMCountByPID = 0; intSIMAllCountByPID = 0; intChannelRCountByPID = 0;//初始化记录数
                            dbeCountByPID = 0;
                            //通过客户编号，通道编号，省份取得SIM记录数（当天）
                            OSIMCountByPID = DbHelperSql.GetSingle(string.Format("SELECT COUNT(a.ID) FROM T_SIM a,T_Area b WHERE a.AreaNO=b.AreaNO AND a.ONO=b.ONO AND a.CNO='{0}' AND a.ChannelNO='{1}' AND b.ProvinceID={2} AND Format(a.CreateTime,'yyyy-MM-dd')='{3}'", strCNO, strChannelNO, strProvinceID, strDayTime));
                            if (OSIMCountByPID != null && !string.IsNullOrEmpty(OSIMCountByPID.ToString()))
                            {
                                intSIMCountByPID = Convert.ToInt32(OSIMCountByPID);
                                if (intSIMCountByPID > 0)
                                {
                                    //通过通道编号+省份取得通道返回记录数（当天）
                                    OChannelRCountByPID = DbHelperSql.GetSingle(string.Format("SELECT COUNT(a.ID) FROM T_Receive a,T_Channel b WHERE a.destaddr=b.ChannelNumber AND a.msg=b.ChannelOrder AND a.ProvinceID={0} AND b.ChannelNO='{1}' AND Format(a.CreateTime,'yyyy-MM-dd')='{2}'", strProvinceID, strChannelNO, strDayTime));
                                    if (OChannelRCountByPID != null && !string.IsNullOrEmpty(OChannelRCountByPID.ToString()))
                                    {
                                        intChannelRCountByPID = Convert.ToInt32(OChannelRCountByPID);
                                        if (intChannelRCountByPID > 0)
                                        {
                                            //通过编号+省份取得SIM记录数（当天）
                                            OSIMAllCountByPID = DbHelperSql.GetSingle(string.Format("SELECT COUNT(a.ID) FROM T_SIM a,T_Area b WHERE a.AreaNO=b.AreaNO AND a.ONO=b.ONO AND b.ProvinceID={0} AND a.ChannelNO='{1}' AND Format(a.CreateTime,'yyyy-MM-dd')='{2}'", strProvinceID, strChannelNO, strDayTime));
                                            if (OSIMAllCountByPID != null && !string.IsNullOrEmpty(OSIMAllCountByPID.ToString()))
                                            {
                                                intSIMAllCountByPID = Convert.ToInt32(OSIMAllCountByPID);
                                                if (intSIMAllCountByPID > 0)
                                                {
                                                    dbeCountByPID = Math.Truncate((intSIMCountByPID / intSIMAllCountByPID.ToDouble()) * intChannelRCountByPID * dbeCNORate);
                                                    dbeAllCount += dbeCountByPID;
                                                }
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                    if (dbeAllCount > 0)
                    {
                        try
                        {
                            dbeAllMoney = dbeAllCount * strChannelPrice.ToDouble();//算出总金额
                        }
                        catch { }
                        SQLlist.Add(string.Format("INSERT INTO T_Cost_Temp(CostDayTime,CNO,ChannelNO,SendNum,CostMoney) VALUES('{0}','{1}','{2}',{3},{4})", strDayTime, strCNO, strChannelNO, dbeAllCount, dbeAllMoney));
                    }
                }
                if (SQLlist.Count > 0)
                {
                    MM.DBUtility.DbHelperSql.ExecuteSqlTran(SQLlist);
                    bolResult = true;
                }
            }
            return bolResult;
        }
        #endregion

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {

                if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                {
                    if (Convert.ToDateTime(inputDateFrom.Value) > Convert.ToDateTime(inputDateTo.Value))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "日期From必须小于等于To！");
                        return;
                    }
                    if (Convert.ToDateTime(inputDateTo.Value) > DateTime.Today.AddDays(1))
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "日期To不能大于今天！");
                        return;
                    }
                    if ((Convert.ToDateTime(inputDateTo.Value) - Convert.ToDateTime(inputDateFrom.Value)).Days > 65)
                    {
                        MM.Common.Common.PageStartAlert(this.Page, "日期From到To的时间间隔不能大于65天！");
                        return;
                    }
                }
                else
                {
                    MM.Common.Common.PageStartAlert(this.Page, "请选择日期From和To！");
                    return;
                }

                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private double AllSendNum = 0;
        private double ALLCostMoney = 0;
        protected void GVinfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string strAllSendNum = ((Label)e.Row.FindControl("lbAllSendNum")).Text.Trim();
                string strAllCostMoney = ((Label)e.Row.FindControl("lbAllCostMoney")).Text.Trim();
                if (!string.IsNullOrEmpty(strAllSendNum))
                    AllSendNum += strAllSendNum.ToDouble();
                if (!string.IsNullOrEmpty(strAllCostMoney))
                    ALLCostMoney += strAllCostMoney.ToDouble();
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[1].Text = "总计：";
                e.Row.Cells[2].Text = AllSendNum.ToString();
                e.Row.Cells[3].Text = ALLCostMoney.ToString();
                AllSendNum = 0;
                ALLCostMoney = 0;
            }
        }
    }
}
